package org.example.queueadmin.config;

import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/configs")
@RequiredArgsConstructor
public class SystemConfigController {
    
    private final SystemConfigService configService;
    
    @GetMapping
    public List<SystemConfig> getAllConfigs() {
        return configService.getAllConfigs();
    }
    
    @GetMapping("/{key}")
    public ResponseEntity<SystemConfig> getConfig(@PathVariable String key) {
        return configService.getConfig(key)
                .map(ResponseEntity::ok)
                .orElse(ResponseEntity.notFound().build());
    }
    
    @PostMapping
    public SystemConfig saveConfig(@RequestBody ConfigRequest request) {
        return configService.saveConfig(
            request.key(), 
            request.value(), 
            request.description(), 
            request.valueType()
        );
    }
    
    @PutMapping("/{key}")
    public ResponseEntity<SystemConfig> updateConfig(@PathVariable String key, @RequestBody ConfigRequest request) {
        return configService.getConfig(key)
                .map(existing -> {
                    SystemConfig updated = configService.saveConfig(
                        key, 
                        request.value(), 
                        request.description(), 
                        request.valueType()
                    );
                    return ResponseEntity.ok(updated);
                })
                .orElse(ResponseEntity.notFound().build());
    }
    
    @DeleteMapping("/{key}")
    public ResponseEntity<Void> deleteConfig(@PathVariable String key) {
        configService.deleteConfig(key);
        return ResponseEntity.ok().build();
    }
    
    @PostMapping("/batch")
    public ResponseEntity<Void> saveConfigs(@RequestBody Map<String, String> configs) {
        configs.forEach((key, value) -> {
            // 根据key推断类型和描述
            String valueType = inferValueType(value);
            String description = generateDescription(key);
            configService.saveConfig(key, value, description, valueType);
        });
        return ResponseEntity.ok().build();
    }
    
    @PostMapping("/init-defaults")
    public ResponseEntity<Void> initializeDefaults() {
        configService.initializeDefaultConfigs();
        return ResponseEntity.ok().build();
    }
    
    private String inferValueType(String value) {
        if ("true".equalsIgnoreCase(value) || "false".equalsIgnoreCase(value)) {
            return "BOOLEAN";
        }
        try {
            Integer.parseInt(value);
            return "INTEGER";
        } catch (NumberFormatException e) {
            if (value.startsWith("{") || value.startsWith("[")) {
                return "JSON";
            }
            return "STRING";
        }
    }
    
    private String generateDescription(String key) {
        return switch (key) {
            case "log.cleanup.enabled" -> "是否启用日志自动清理";
            case "log.cleanup.retention.days" -> "日志保留天数";
            case "log.cleanup.interval.hours" -> "清理检查间隔（小时）";
            case "log.cleanup.batch.size" -> "每次清理的批次大小";
            case "message.preview.max.length" -> "消息预览最大长度";
            case "message.preview.hex.limit" -> "二进制消息十六进制显示限制";
            default -> "系统配置项";
        };
    }
    
    public record ConfigRequest(String key, String value, String description, String valueType) {}
}
